package org.box.demos.multithreading.wgetmt;

import java.io.IOException;
import java.util.regex.Pattern;

import org.box.demos.multithreading.wgetmt.core.Storage;
import org.box.demos.multithreading.wgetmt.core.storage.DbStorage;
import org.box.demos.multithreading.wgetmt.core.storage.FileStorage;
import org.box.demos.multithreading.wgetmt.j16mt.J16MTEngine;

public class WGetApp {

	private final Configuration cfg;

	public WGetApp(Configuration cfg) {
		this.cfg = cfg;
	}

	public void run() throws IOException {
		printInfo(cfg);
		
		Storage storage = createStorage(cfg);
		// init executer
		J16MTEngine engine = new J16MTEngine(cfg, storage);
		// run pooling
		engine.run();
	}
	
	static void printInfo(Configuration cfg) {
		System.out.println("URL(s): " + cfg.getUrls());
		System.out.println("Mode: " + (cfg.isRecursive()? "Recursive" : "Non-recursive"));
		if (cfg.isRecursive())
			System.out.println("Recursive Deep Level: " + cfg.getMaxLevel());
		
		System.out.println("Output Diriectory: " + cfg.getOutDir());
		// check Download Pattern
		Pattern pattern = cfg.getDownloadPattern();
		if (pattern != null)
			System.out.println("Download pattern: " + pattern); 

		pattern = cfg.getSkipPattern();
		if (pattern != null)
			System.out.println("Skip pattern: " + pattern);
		
		if (cfg.getDatabaseName() != null && !cfg.getDatabaseName().trim().isEmpty())
			System.out.println("Database: " + cfg.getDatabaseName());
		
		System.out.println("Download Limit: " + ((cfg.getDownladLimit() < 0) ? "Unlimted" : (cfg.getDownladLimit() + " Mb.")));
		
		System.out.println("-----------------------------------------------");
	}

	private Storage createStorage(Configuration cfg) {
		if (cfg.getDatabaseName() != null && !cfg.getDatabaseName().trim().isEmpty()) {
			return new DbStorage();
		}  else {
			return new FileStorage();
		}

	}


}
